package com.ruoyi.common.validation;

import com.ruoyi.common.annotation.Length;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.invoke.MethodHandles;

/**
 * @Classname ValidLengthConstraintValidator
 * @Author: sunluquan
 * @Date: 2022/6/17 12:18
 * @Description TODO
 */
@Slf4j
public abstract class AbstractValidLengthConstraintValidator<T> implements ConstraintValidator<Length,T> {

    private static final Log LOG = LoggerFactory.make( MethodHandles.lookup() );

    protected int min;

    protected int max;

    @Override
    public void initialize(Length parameters) {
        this.min = parameters.min();
        this.max = parameters.max();
        validateParameters();
    }

    @Override
    public boolean isValid(T value, ConstraintValidatorContext context) {
        if(value ==null){
            return true;
        }
        int length = 0;
        if(value instanceof CharSequence){
            length = ((CharSequence) value).length();
        }else if(value instanceof Number){
            length = value.toString().length();
        }
        return length >= min && length <= max;
    }


    private void validateParameters() {
        if ( min < 0 ) {
            throw LOG.getMinCannotBeNegativeException();
        }
        if ( max < 0 ) {
            throw LOG.getMaxCannotBeNegativeException();
        }
        if ( max < min ) {
            throw LOG.getLengthCannotBeNegativeException();
        }
    }
}
